package com.gosilver.beans.factory.support.instantiate;


import com.gosilver.beans.BeansException;
import com.gosilver.beans.factory.config.BeanDefinition;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.NoOp;

import java.lang.reflect.Constructor;

public class CglibSubclassingInstantiationStrategy implements InstantiationStrategy {
    @Override
    public Object instantiate(BeanDefinition beanDefinition,
                              String beanName,
                              Constructor ctor,
                              Object[] args) throws BeansException {
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(beanDefinition.getBeanClass());
        enhancer.setCallback(new NoOp() {
            @Override
            public int hashCode() {
                return super.hashCode();
            }
        });

        // 判断 ctor 是否为空，如果为空则是无构造函数实例化，否则就是需要有构造函数的实例化
        if (null == ctor){
            return enhancer.create();
        } else {
            return enhancer.create(ctor.getParameterTypes(), args);
        }
    }
}
